var element,form,table,laydate,layer,colorpicker,slider;
// 适用门店 模拟数据
var storeMockData = [
    {id:1,area:'区域1',shop:'门店1',service:'堂食+外卖'},
    {id:2,area:'区域2',shop:'门店1',service:'堂食+外卖'},
    {id:3,area:'区域3',shop:'门店1',service:'堂食+外卖'},
    {id:4,area:'区域4',shop:'门店1',service:'堂食+外卖'},
    {id:5,area:'区域5',shop:'门店1',service:'堂食+外卖'}
]
// 红包 券表格句柄
var tableHandle = [];
// 红包奖励规则设置的数据
var redpacketSetData = [
    {
        redPacketCount:1, // 最佳手气红包定死了1个
        goodLuckplace:0, // 最佳手气在第几位后
        tableData:[
            {id:1,couponName:'2元券',price:2,validity:'领取2日后生效,20日失效',couponCount:2},
            {id:2,couponName:'3元券',price:3,validity:'领取2日后生效,20日失效',couponCount:2},
            {id:3,couponName:'4元券',price:4,validity:'领取2日后生效,20日失效',couponCount:2},
        ],
        redPacketReward:2 // 红包奖励余额
    },
    {
        redPacketCount:2,
        tableData:[
            {id:1,couponName:'1元券',price:1,validity:'领取2日后生效,20日失效',couponCount:2},
            {id:2,couponName:'2元券',price:2,validity:'领取2日后生效,20日失效',couponCount:2},
            {id:3,couponName:'3元券',price:3,validity:'领取2日后生效,20日失效',couponCount:2},
        ],
        redPacketReward:2 // 红包奖励余额
    },
    {
        redPacketCount:3,
        tableData:[
            {id:1,couponName:'1元券',price:1,validity:'领取2日后生效,20日失效',couponCount:2},
            {id:2,couponName:'2元券',price:2,validity:'领取2日后生效,20日失效',couponCount:2},
            {id:3,couponName:'3元券',price:3,validity:'领取2日后生效,20日失效',couponCount:2},
        ],
        redPacketReward:2 // 红包奖励余额
    }

]
// 经过计算后的红包奖励设置 之后数据发生变化也是修改这个变量
var computeRedPacketData = [];
layui.use(['element','form','table','laydate','layer','colorpicker','slider'],function(){
    var element = layui.element;
    var form = layui.form;
    var table = layui.table;
    var laydate = layui.laydate;
    var colorpicker = layui.colorpicker;
    var slider = layui.slider;

    // 提示图标的鼠标移入移出事件
    $(".user-icon-info-wrap").on('mouseenter',function(){
        var that = this;
        var info = $(that).data('infotext');
        var index = layer.tips(info,that,{time:40000})
        $(that).off('mouseleave'); // 避免重复绑定
        $(that).on('mouseleave',function(){
           layer.close(index);
        })
    })
    // 渲染适用门店表格
    function applyShopTable(data){
        // 判断data数据中的子项,是否具有LAY_CHECKED属性,没有则加上,值为false
        data.forEach(item => {
            if(item.LAY_CHECKED === undefined){
                item.LAY_CHECKED = false;
            }
        })
        table.render({
            elem:'#userAddStoreTable',
            page:true,
            data:data,
            cols:[[
                {type:'checkbox'},
                {field:'area',title:'区域',align:'center'},
                {field:'shop',title:'适用门店',align:'center'},
                {field:'service',title:'服务范围',align:'center'},
                {title:'操作',align:'center',templet:'#applyShopOperatorTpl'}
            ]]
        })
    }
    applyShopTable(storeMockData);
    // 红包奖励内容设置
    function computeRedPacketDataFun(data){
        // 根据返回的红包配置数据,计算红包总金额等项
        var res = JSON.parse(JSON.stringify(data));
        res.forEach((item,index)=>{
            item.redPacketTotalMoney = 0;
            item.couponTotalCount = 0;
            item.tableData.forEach((i,j)=>{
                item.redPacketTotalMoney += i.price * i.couponCount;
                item.couponTotalCount += i.couponCount-0;
                i.index = index;
                i.indexthis = j;
            })
            item.singleRedPacketMoney = item.redPacketTotalMoney; // 单个红包金额
            item.singleRedPacketCount = item.couponTotalCount;  // 单个红包卡券数量
            item.redPacketTotalMoney = Number(item.redPacketTotalMoney*item.redPacketCount.toFixed(2)); // 总的红包金额
            item.couponTotalCount = Number(item.couponTotalCount*item.redPacketCount.toFixed(2)); // 总的红包卡券数量
            item.rewardTotalMoney = Number(item.redPacketReward*item.redPacketCount.toFixed(2)); // 总的红包奖励余额
        })
        return res;
    }
    // 处理数据后重新渲染红包设置列表
    function redPacketRender(){
        $("#red-packet-wrap").html('');
        computeRedPacketData = computeRedPacketDataFun(computeRedPacketData);
        redRewardInitFun(computeRedPacketData,'init')
    }
    computeRedPacketData = computeRedPacketDataFun(redpacketSetData);
    function redRewardInitFun(data,type){
        var cols = [[
            {field:'couponName',title:'券名称',align:'center'},
            {field:'validity',title:'有效期',align:'center'},
            {field:'',title:'包含张数',align:'center',templet:function(d){
                return `<input type='text' class='layui-input layui-input-table-cell' value=${d.couponCount} data-arrindex=${d.index} data-indexthis=${d.indexthis} data-type='tableInput'>`;
            }},
            {title:'操作',align:'center',templet:function(d){
                return `
                    <button type="button" class="layui-btn layui-btn-normal layui-btn-sm red-packet-operator-btn" style="margin-right:16px;" data-type="detail" data-arrindex=${d.index} data-indexthis=${d.indexthis}>详情</button>
                    <button type="button" class="layui-btn layui-btn-danger layui-btn-sm red-packet-operator-btn" data-type="delete" data-arrindex=${d.index} data-indexthis=${d.indexthis}>删除</button>
                `;
            }}
        ]]
        data.forEach((item,index)=>{
            if(index == 0 && type == 'init'){
                var goodLunckTpl = `
                    <div id="redPacketItem${index}">
                        <p>手气最佳的红包设置</p>
                        <div>发放 <input type="text" class="layui-input layui-input-mini red-packet-count-js" data-arrindex="${index}" value="${item.redPacketCount}" readonly >个红包,总金额<b class="red-packet-total-money-js">${item.redPacketTotalMoney}</b>元</div>
                        <div>最佳手气红包在第<input type="text" class="layui-input layui-input-mini">位以后的领取者随机产生</div>
                        <div>
                        该红包奖励代金券<b class="red-packet-single-count-js">${item.singleRedPacketCount}</b>张，代金额<b class="red-packet-single-money-js">${item.singleRedPacketMoney}</b>元
                        <div class="form-mini-normal-btn margin-left-30">+添加代金券</div>
                        </div>
                        <table id="redPacketTable${index}"></table>
                        <div>该红包奖励余额<input type="text" value="${item.redPacketReward}" data-type="reward" data-arrindex="${index}"  class="layui-input layui-input-mini red-packet-reward-js">元</div>
                    </div>
                `;
                $("#red-packet-wrap").append(goodLunckTpl);
            }else{
                var redPacketCommonTpl = `
                    <div id="redPacketItem${index}" class="red-packet-item">
                        <p>手气第 ${index+1} 的红包设置</p>
                        <div>发放<input type="text" value="${item.redPacketCount}" data-arrindex="${index}" data-type="redpacketcount" class="layui-input layui-input-mini red-packet-count-js">个红包,总金额<b class="red-packet-total-money-js">${item.redPacketTotalMoney}</b>元,代金券<b class="coupon-total-count-js">${item.couponTotalCount}</b>张</div>
                        <div>
                        每个红包奖励代金券<b class="red-packet-single-count-js">${item.singleRedPacketCount}</b>张,代金额<b class="red-packet-single-money-js">${item.singleRedPacketMoney}</b>元,<b class="red-packet-count-js">${item.redPacketCount}</b>个红包发放代金券<b class="coupon-total-count-js">${item.couponTotalCount}</b>张,代金额<b class="red-packet-total-money-js">${item.redPacketTotalMoney}</b>元
                        <div class="form-mini-normal-btn margin-left-30">+添加代金券</div>
                        </div>
                        <table id="redPacketTable${index}"></table>
                        <div>每个红包奖励余额<input type="text" value="${item.redPacketReward}" data-type="reward" data-arrindex="${index}" class="layui-input layui-input-mini red-packet-reward-js">元,<b class="red-packet-count-js">${item.redPacketCount}</b>个红包发放金额<b class="red-packet-total-money-js">${item.rewardTotalMoney}</b>元</div>
                        <div class="red-packet-item-close red-packet-operator-btn" data-type="deleteitem" data-arrindex="${index}"  style="display:${ index>1 ? 'inline-block' : 'none' }"> <i class="layui-icon layui-icon-close" style="font-size:20px;"></i> </div>
                    </div>
                `;
                $("#red-packet-wrap").append(redPacketCommonTpl);
            }
            // 初始化表格
            var tableHandleThis = table.render({
                elem:'#redPacketTable'+index,
                cols:cols,
                data:item.tableData,
                limit:item.tableData.length
            })
            tableHandle.push(tableHandleThis)
        })
    }
    redRewardInitFun(computeRedPacketData,'init')
    // 监听红包设置里的input框值改变事件
    $(document).on('blur','#red-packet-wrap .layui-input',function(){
        // 获取当前修改的input 在数据中的位置
        var value = $(this).val() - 0;
        // TODO 这里可以对输入的值进行非数校验,不符合则结束方法执行
        var arrIndex = $(this).data('arrindex');
        var type = $(this).data('type');
        if(type == 'tableInput'){
            var indexThis = $(this).data('indexthis');
            computeRedPacketData[arrIndex].tableData[indexThis].couponCount = value;
        }else if(type == 'redpacketcount'){
            // 如果改变的是红包的数量,需要在computeRedPacketData中也改变相应的数量
            computeRedPacketData[arrIndex].redPacketCount = value;
        }else if(type == 'reward'){
            computeRedPacketData[arrIndex].redPacketReward = value;
        }
        redPacketRender();
    })
    // 监听红包设置里的详情,删除 和 整个红包设置项的删除按钮
    $(document).on('click','.red-packet-operator-btn',function(){
        // 获取当前点击按钮的类型
        debugger
        var type = $(this).data('type');
        var arrIndex = $(this).data('arrindex');
        var indexThis = $(this).data('indexthis');
        if(type == 'detail'){
            //详情 根据arrIndex和indexthis 可以定位到具体的信息
            var itemData = computeRedPacketData[arrIndex].tableData[indexThis];
            console.log(itemData);
        }else if(type == 'delete'){
            // 删除该项
            computeRedPacketData[arrIndex].tableData.splice(indexThis,1);
            redPacketRender();
        }else if(type == 'deleteitem'){
            // 删除整个红包设置项
            layer.confirm('确定删除吗?', {icon: 3, title:'提示'}, function(index){
                //点击确定后的回调
                computeRedPacketData.splice(arrIndex,1);
                redPacketRender();
                // 这里异步关闭弹出层,减少红包项渲染时的闪烁.
                setTimeout(function(){
                   layer.close(index); 
                },0)
            });
        }else if(type == 'addpacket'){
            // 添加一级手气红包 ,往computeRedPacketData中新增一项,重新渲染即可
            computeRedPacketData.push({
                redPacketCount:1,
                tableData:[
                    {id:1,couponName:'1元券',price:1,validity:'领取2日后生效,20日失效',couponCount:2},
                    {id:2,couponName:'2元券',price:2,validity:'领取2日后生效,20日失效',couponCount:2},
                    {id:3,couponName:'3元券',price:3,validity:'领取2日后生效,20日失效',couponCount:2},
                ],
                redPacketReward:0 // 红包奖励余额
            })
            redPacketRender();
        }
    })

    // 红包配置 
    // 红包配置默认值
    var redPacketDefaultData = {
        get_red_packet_img:'../../img/head.png', // 背景图
        get_red_packet_bg:'#FB5B46', // 整体背景色
        get_success_main_checkbox:true,//领取成功红包样式UI设置
        get_success_main_text:'恭喜您获得红包',
        get_success_second_checkbox:true,
        get_success_second_text:'可以分享给更多朋友来领取哦~',
        get_coupon_second_title_select:'2',
        get_overdue_main_text:'来迟了，红包已过期！', //已过期红包样式UI设置
        get_overdue_second_text:'手气重要，手速也很重要哦',
        get_already_main_text:'啊噢，红包已被抢光啦~', //已领完红包样式UI设置
        get_already_second_text:'手气重要，手速也很重要哦',
        get_button_color:'#fff',
        get_button_one_gradient:'#FB5B46', // 按钮渐变色1
        get_button_two_gradient:'#FF184F', // 按钮渐变色2
        get_record_show_radio:1, // 是否展示邀请几个好友拆红包
        get_record_invite_text:'还可以邀请X位朋友领取红包哦~',
        get_record_color:'#fff', // 还可以邀请好友的字体颜色,
        get_rule_html:`
             <p>1、您邀请的好友为( luckin coffee或小鹿茶)新用户即可获赠新人 大券包。特别提示:如您邀请的好友已经在小鹿茶注册,则不属于 新用户</p>
             <p>2、饮品券使用范围:大师咖啡系列、啵啵奶茶系列、牛乳茶系列</p>
        `,
        layer_big_img:'../../img/redPacket.png',
        layer_small_img:'../../img/redPacket.png'
    }
    // 根据默认值 生成操作记录对象
    // 用户操作记录初始化
    function initRecord(data){
        let res = {};
        for(let key in data){
            res[key] = [data[key]];
        }
        return res;
    }
    var redPacketRecord = initRecord(redPacketDefaultData);
    // 记录用户所操作项目的key值,用此来作为撤销操作的依据
    redPacketRecordArr= [];
    // 保存用户操作记录
    function addRecord(key,val){
        let o = {};
        o[key] = val;
        redPacketRecord[key].push(val);
        redPacketRecordArr.push(o);
    }
    // 初始化 设置
    setTimeout(function(){
        initRedPacketFn(redPacketDefaultData,'init');
    },10)
    function initRedPacketFn(data,watch){
        var keys = Object.keys(data);
        keys.forEach(key=>{
            let suffix = key.slice(key.lastIndexOf('_')+1);
            switch(suffix){
                case 'text':
                    $("."+key).val(data[key]);
                    $("."+key+"_target").text(data[key]);
                break;
                case 'gradient':
                    if(watch == 'init'){
                       colorPickers(key,data,'gradient',watch); 
                    }
                    if(key == 'get_button_one_gradient'){
                        let secondColor = redPacketRecord['get_button_two_gradient'][redPacketRecord['get_button_two_gradient'].length-1];
                        $(".get_button_color_target").css("background","linear-gradient(to bottom,"+data[key]+","+secondColor+")");
                    }else if(key == 'get_button_two_gradient'){
                        let oneColor = redPacketRecord['get_button_one_gradient'][redPacketRecord['get_button_one_gradient'].length-1];
                        $(".get_button_color_target").css("background","linear-gradient(to bottom,"+oneColor+","+data[key]+")");
                    }
                break; 
                case 'bg':
                    if(watch == 'init'){
                        colorPickers(key,data,'bg',watch);
                    }
                    $("#"+key+"_target").css('background',data[key]);
                break;
                case 'color':
                    debugger
                    if(watch == 'init'){
                        colorPickers(key,data,'color',watch);
                    }
                    $("."+key+"_target").css('color',data[key]);
                break;
                case 'checkbox':
                    let target = key.replace('checkbox','text');
                    form.val('global-form',{
                        [key]:data[key]
                    })
                    if(data[key]){
                        $("."+target+"_target").show();
                    }else{
                        $("."+target+"_target").hide();
                    }
                break;
                case 'select':
                    form.val('global-form',{
                        [key]:data[key]
                    })
                    if(key == 'get_coupon_second_title_select'){
                        if(data[key] == '1'){
                            $("."+key+"_target").show();
                        }else{
                            $("."+key+"_target").hide();
                        }
                    }
                break;
                case 'radio':
                    form.val('global-form',{
                        [key]:data[key]
                    })
                    if(key == 'get_record_show_radio'){
                        if(data[key] == '1'){
                            $("."+key+"_target").show();
                        }else{
                            $("."+key+"_target").hide();
                        }
                    }
                break;
                case 'html':
                    $("#"+key+"_target").html(data[key]);
                    editorTimer = setInterval(() => {
                        if(window.editor){
                            editor.html(data[key]);
                            clearInterval(editorTimer);
                            console.log('执行了几次')
                        }
                    }, 10);
                break;
                case 'img':
                    $("."+key+"_target").attr('src',data[key]);
                break;
                    
            }
        })
    }
    // 富文本编辑器初始化
KindEditor.ready(function(K) {
    window.editor = K.create('#get_rule_html',{
        resizeType : 0,
        filterMode : true,
        allowPreviewEmoticons : false,
        allowImageUpload : false,
        items : [
            'fontsize', '|', 'forecolor', 'hilitecolor', 'bold', 'italic', 'underline',
            'removeformat', '|', 'justifyleft', 'justifycenter', 'justifyright', 'insertorderedlist',
            'insertunorderedlist'],
        afterBlur:function(r){
            // 失去焦点就添加一条记录
            addRecord('get_rule_html',editor.html());
            $("#get_rule_html_target").html(editor.html());
        }
    });
 });
    // 监听复选框
    form.on('checkbox(chebox-unity-watch)',function(res){
        addRecord(res.value,res.elem.checked);
        let target = res.value.replace('checkbox','text');
        if(res.elem.checked){
            $("."+target+"_target").show();
        }else{
            $("."+target+"_target").hide();
        }
    })
    // 监听下拉框
    form.on('select(select-unity-watch)',function(res){
        let name = $(res.elem).attr('name');
        let value = res.value;
        addRecord(name,value);
        if(name == 'get_coupon_second_title_select'){
            if(value == '1'){
                $("."+name+"_target").show();
            }else{
                $("."+name+"_target").hide();
            }
        }
    })
    // 监听下拉单选框
    form.on('radio(radio-unify-watch)',function(res){
        let name = $(res.elem).attr('name');
        let value = res.value;
        addRecord(name,value);
        if(name == 'get_record_show_radio'){
            if(value == '1'){
                $("."+name+'_target').show();
            }else{
                $("."+name+'_target').hide();
            }
        }
    })
    // 监听input框的值变化
    $(document).on('blur','.red-packet-mobile-set .layui-input',function(){
        let target = $(this).data('target');
        let val = $(this).val();
        addRecord(target,val);
        $("."+target+"_target").text(val);
    })
    // 渲染颜色选择器方法
    function colorPickers(key,obj,type,watch){
        colorpicker.render({
            elem: '#'+key
            ,color: obj[key]
            ,done: function(color){
                addRecord(key,color);
                if(type == 'bg'){
                    $("#"+key+"_target").css('background',color);
                }else if(type == 'color'){
                    $("."+key+"_target").css('color',color);
                }else if(type == 'gradient'){
                    if(key == 'get_button_one_gradient'){
                        let secondColor = redPacketRecord['get_button_two_gradient'][redPacketRecord['get_button_two_gradient'].length-1];
                        $(".get_button_color_target").css("background","linear-gradient(to bottom,"+color+","+secondColor+")");
                    }else if(key == 'get_button_two_gradient'){
                        let oneColor = redPacketRecord['get_button_one_gradient'][redPacketRecord['get_button_one_gradient'].length-1];
                        $(".get_button_color_target").css("background","linear-gradient(to bottom,"+oneColor+","+color+")");
                    }
                }
            }
        });
    }
       //点击显示相应的ui配置
    $('.show-set-item').click(function(){
        var index = $(this).data('index');
        $(".set-set-item-common").css('display','none');
        $(".set-set-item-common[data-index="+index+"]").css('display','block');
    })
    //红包设置 恢复默认
    $("#red_packet_default").click(function(){
        redPacketRecord = initRecord(redPacketDefaultData);
        // 记录用户所操作项目的key值,用此来作为撤销操作的依据
        redPacketRecordArr= [];
        initRedPacketFn(redPacketDefaultData,'init');
    })
    // 撤销编辑 事件
    $("#red_packet_back").click(function(){
        if(redPacketRecordArr.length === 0){
            layer.msg('已经是最初的样子了');
            return false;
        }
        let obj = redPacketRecordArr.pop();
        let o = {};
        for(let key in obj){
          o[key] = redPacketRecord [key][redPacketRecord [key].length-2];
          // 将记录的最后一项推出
          initRedPacketFn(o,'init');
          redPacketRecord[key].pop();
        }
    })
    // 弹出层红包设置 恢复默认
    $(".layer_default").click(function(){

    })
    // 弹出层红包 撤销编辑
    $(".layer_back").click(function(){

    })
    // 弹出层红包 保存
    $(".layer_save").click(function(){
        
    })
    // 
    // 从操作记录中提取出保存项
    function extractData(data){
        let res = {};
        for(let key in data){
            // 提取每一项的最后一个值
            res[key] = data[key][data[key].length-1];
        }
        return res;
    }
    // 保存操作
    $("#red_packet_save").click(function(){
        let resData = extractData(redPacketRecord);
        console.log(resData);
    })
})


